package com.caikun.model.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;

import java.util.Date;
import java.util.Map;

public class JwtUtils {

    public static final String Header = "token";
    
    private static final String SECRET_KEY = "your-256your-256your-256your-256"; // Replace with your secret key
    private static final long EXPIRATION_TIME = 86400000; // 24 hours in milliseconds

    /**
     * 生成JWT令牌
     * @param subject
     * @param claims
     * @return
     */
    public static String generateToken(String subject, Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims) // Add custom claims
                .setSubject(subject) // Set the subject (e.g., username)
                .setIssuedAt(new Date()) // Set issue time
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME)) // Set expiration time
                .signWith(Keys.hmacShaKeyFor(SECRET_KEY.getBytes()), SignatureAlgorithm.HS256) // Sign with secret key
                .compact(); // Generate the token
    }

    /**
     * 解析JWT令牌
     * @param token
     * @return
     */
    public static Claims parseToken(String token) {
        return Jwts.parserBuilder()
                .setSigningKey(Keys.hmacShaKeyFor(SECRET_KEY.getBytes())) // Use the same secret key for validation
                .build()
                .parseClaimsJws(token)
                .getBody(); // Extract claims from the token
    }

    /**
     * 检查令牌是否已过期
     * @param token
     * @return
     */
    public static boolean isTokenExpired(String token) {
        try {
            Claims claims = parseToken(token);
            return claims.getExpiration().before(new Date());
        } catch (JwtException e) {
            return true; // Invalid or expired token
        }
    }

    public static boolean validateToken(String token) {
        try {
            Claims claims = parseToken(token);
            return claims.getExpiration().after(new Date());
        } catch (JwtException | IllegalArgumentException e) {
            return false;
        }
    }
}